package com.jp.fm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

import com.jp.fm.HomeFinanceRunner;
import com.jp.fm.data.Account;

public class RefreshAccount extends ServletParent {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public RefreshAccount() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public final void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public final void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {

		doPost(request, response);
	}

	public final void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {

		Account account = getAccountDao().findByName(
				request.getParameter("acct"));

		HomeFinanceRunner.refreshAccountFromSource(account,
				getCategoryService(), getCategoryDao(), getAccountDao());

		account = getAccountDao().findByName(account.getName());

		String lastUpdateText = HomeFinanceRunner.getLastUpdateText(account
				.getLastupdate());

		JSONObject obj = new JSONObject();
		obj.put("lastUpdateText", lastUpdateText);
		obj.put("balance",
				NumberFormat.getCurrencyInstance().format(account.getBalance()));

		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		obj.writeJSONString(out);
	}
}
